package logic

import (
	"context"
	"fmt"
	"store/model/mysql"
	"store/model/redis"
	"store/pkg"

	"store/storerpc/internal/svc"
	"store/storerpc/storerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *storerpc.LoginRequest) (*storerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendsmslist" + in.Account + in.Source)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信未验证,不能登录")
	}
	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("account  = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账户不存在,请重新输入")
	}
	if user.Password != pkg.MD5(in.Password) {
		return nil, fmt.Errorf("密码不正确,请重新输入")
	}
	redis.Client.Del("sendsmslist" + in.Account + in.Source)
	return &storerpc.LoginResponse{Id: int64(user.ID)}, nil
}
